<template>
  <el-dialog
    v-model="dialogVisible"
    :title="ruleForm.id ? '修改问题分类' : '新增问题分类'"
    width="430"
    class="qc-custom-dialog"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="dialog-form-wrap"
    >
      <el-form-item label="问题分类" prop="questionClassification">
        <el-input
          v-model.trim="ruleForm.questionClassification"
          placeholder="请输入问题分类"
          maxlength="8"
          clearable
        />
      </el-form-item>
      <el-form-item label="展示优先级" prop="showPriority" class="has-tips">
        <el-input
          v-model.trim="ruleForm.showPriority"
          placeholder="请输入展示优先级"
          maxlength="2"
          clearable
        />
        <div class="tip">
          <div class="icon"></div>
          注：请输入0~99数字，数字越小优先级越高，排序靠前
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script lang="ts" setup name="dialog-edit">
import type { FormInstance, FormRules } from 'element-plus';
import { IS_INT_0 } from '@/utils/verify';
import { saveQuestion, updateQuestion } from '@/service/apis/market';

const ruleFormRef = ref<FormInstance>();

let dialogVisible = ref(false);

let ruleForm = reactive({
  id: '',
  questionClassification: '',
  showPriority: '',
});

const rules = reactive<FormRules>({
  questionClassification: [
    { required: true, message: '请输入问题分类', trigger: 'blur' },
  ],
  showPriority: [
    { required: true, message: '请输入展示优先级', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '请输入正确的展示优先级，整数',
      trigger: 'blur',
    },
  ],
});

const show = (row?: any) => {
  if (row) {
    ruleForm.id = row.id;
    ruleForm.questionClassification = row.questionClassification;
    ruleForm.showPriority = row.showPriority;
  } else {
    ruleForm.id = '';
    ruleForm.questionClassification = '';
    ruleForm.showPriority = '';
  }
  dialogVisible.value = true;
};
const hide = () => {
  dialogVisible.value = false;
};

const emit = defineEmits(['get-data']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.id) {
        updateQuestion(ruleForm).then((res: any) => {
          hide();
          emit('get-data');
        });
      } else {
        saveQuestion(ruleForm).then((res: any) => {
          hide();
          emit('get-data');
        });
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.count-wrap {
  :deep(.el-form-item:first-child .el-form-item__content) {
    width: 80px;
    margin-right: 12px;
  }
}
</style>